<template>
    <div class="container">
        <div class="upload">
            <div>
                <input type="file"
                       ref="vExampleFile"
                       id="fileUpload"
                       style="display: none;"
                       @change="fileChange($event)">
                <!-- <el-button size="small"
                           type="primary"
                           v-on:click="handleOpenFile()">
                    上传
                </el-button> -->
                <div class="upload-demo"
                     @click="handleOpenFile()">
                    <div v-show="!uploading">
                        <i class="el-icon-upload"></i>
                        <div class="div__text"><em>点击上传</em></div>
                    </div>
                    <div class="has-file"
                         v-show="uploading">
                        <el-progress type="circle"
                                     :percentage="authProgress"></el-progress>
                    </div>
                </div>
                <div class="file-name">{{fileName}}</div>
                <label class="status">上传状态: <span>{{statusText}}</span></label>
            </div>
            <div class="upload-type">
                <el-button type="primary"
                           @click="authUpload"
                           :disabled="uploadDisabled">开始上传</el-button>
                <el-button type="primary"
                           @click="pauseUpload"
                           :disabled="pauseDisabled">暂停</el-button>
                <el-button type="primary"
                           :disabled="resumeDisabled"
                           @click="resumeUpload">恢复上传</el-button>
                <!-- <span class="progress">上传进度: <i id="auth-progress">{{authProgress}}</i> %</span> -->
            </div>
        </div>
    </div>
</template>
<script>
import { getVoidUploadToken, refreshUploadVideo } from '@/api/aliyun/aliyun'
import { addVideoFiles } from '@/api/operater/video'

export default {
    data() {
        return {
            timeout: '',
            partSize: '',
            parallel: '',
            retryCount: '',
            retryDuration: '',
            region: 'cn-shanghai',
            userId: '1174477435645746',
            fileName: '',
            file: null,
            authProgress: 0,
            uploadDisabled: true,
            resumeDisabled: true,
            pauseDisabled: true,
            uploader: null,
            statusText: '',
            uploading: false,
        }
    },
    methods: {
        // 打开文件
        handleOpenFile() {
            this.$refs.vExampleFile.click()
        },
        fileChange(e) {
            this.file = e.target.files[0]
            if (!this.file) {
                alert('请先选择需要上传的文件!')
                return
            }
            this.fileName = this.file.name
            var Title = this.file.name
            var userData = '{"Vod":{}}'
            if (this.uploader) {
                this.uploader.stopUpload()
                this.authProgress = 0
                this.statusText = ''
            }
            this.uploader = this.createUploader()
            console.log(userData)
            this.uploader.addFile(this.file, null, null, null, userData)
            this.uploadDisabled = false
            this.pauseDisabled = true
            this.resumeDisabled = true
        },
        authUpload() {
            // 然后调用 startUpload 方法, 开始上传
            if (this.uploader !== null) {
                this.uploader.startUpload()
                this.uploadDisabled = true
                this.pauseDisabled = false
            }
        },
        // 暂停上传
        pauseUpload() {
            if (this.uploader !== null) {
                this.uploader.stopUpload()
                this.resumeDisabled = false
                this.pauseDisabled = true
            }
        },
        // 恢复上传
        resumeUpload() {
            if (this.uploader !== null) {
                this.uploader.startUpload()
                this.resumeDisabled = true
                this.pauseDisabled = false
            }
        },
        createUploader(type) {
            let self = this
            let uploader = new AliyunUpload.Vod({
                timeout: self.timeout || 60000,
                partSize: self.partSize || 1048576,
                parallel: self.parallel || 5,
                retryCount: self.retryCount || 3,
                retryDuration: self.retryDuration || 2,
                region: self.region,
                userId: self.userId,
                // 添加文件成功
                addFileSuccess: function (uploadInfo) {
                    self.uploadDisabled = false
                    self.resumeDisabled = false
                    self.statusText = '添加文件成功, 等待上传...'
                    console.log('addFileSuccess: ' + uploadInfo.file.name)
                },
                // 开始上传
                onUploadstarted: function (uploadInfo) {
                    console.log(uploadInfo)
                    if (!uploadInfo.videoId) {
                        console.log(uploadInfo)
                        let params = {
                            fileName: uploadInfo.file.name,
                            videoTitle: uploadInfo.file.name,
                        }
                        getVoidUploadToken(params)
                            .then((res) => {
                                let data = res.data
                                let uploadAuth = data.uploadAuth
                                let uploadAddress = data.uploadAddress
                                let videoId = data.videoId
                                uploader.setUploadAuthAndAddress(
                                    uploadInfo,
                                    uploadAuth,
                                    uploadAddress,
                                    videoId
                                )
                            })
                            .catch((error) => {
                                console.log(error)
                            })
                        self.statusText = '文件开始上传...'
                        self.uploading = true
                        console.log(
                            'onUploadStarted:' +
                                uploadInfo.file.name +
                                ', endpoint:' +
                                uploadInfo.endpoint +
                                ', bucket:' +
                                uploadInfo.bucket +
                                ', object:' +
                                uploadInfo.object
                        )
                    } else {
                        // 如果videoId有值，根据videoId刷新上传凭证
                        // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
                        // let refreshUrl =
                        //     'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&f=xxx.mp4&VideoId=' +
                        //
                        refreshUploadVideo(uploadInfo.videoId).then((res) => {
                            let data = res.data
                            let uploadAuth = data.uploadAuth
                            let uploadAddress = data.uploadAddress
                            let videoId = data.videoId
                            self.uploading = true

                            uploader.setUploadAuthAndAddress(
                                uploadInfo,
                                uploadAuth,
                                uploadAddress,
                                videoId
                            )
                        })
                    }
                },
                // 文件上传成功
                onUploadSucceed: function (uploadInfo) {
                    console.log('uploadInfo')
                    console.log(uploadInfo)
                    self.statusText = '文件上传成功!'
                    // self.$emit('setVideoId', uploadInfo.videoId)
                    // videoId
                    let params = {
                        videoId: uploadInfo.videoId,
                    }
                    addVideoFiles(params)
                        .then((res) => {
                            if (res.code === 200) {
                                self.$emit('setVideoId', res.data.id)
                            } else {
                                this.$message.error(res.desc)
                            }
                            console.log(res)
                        })
                        .catch((e) => {
                            console.log(e)
                        })
                },
                // 文件上传失败
                onUploadFailed: function (uploadInfo, code, message) {
                    console.log(
                        'onUploadFailed: file:' +
                            uploadInfo.file.name +
                            ',code:' +
                            code +
                            ', message:' +
                            message
                    )
                    self.statusText = '文件上传失败!'
                },
                // 取消文件上传
                onUploadCanceled: function (uploadInfo, code, message) {
                    console.log(
                        'Canceled file: ' +
                            uploadInfo.file.name +
                            ', code: ' +
                            code +
                            ', message:' +
                            message
                    )
                    self.statusText = '文件已暂停上传'
                },
                // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
                onUploadProgress: function (uploadInfo, totalSize, progress) {
                    console.log(
                        'onUploadProgress:file:' +
                            uploadInfo.file.name +
                            ', fileSize:' +
                            totalSize +
                            ', percent:' +
                            Math.ceil(progress * 100) +
                            '%'
                    )
                    let progressPercent = Math.ceil(progress * 100)
                    self.authProgress = progressPercent
                    self.statusText = '文件上传中...'
                },
                // 上传凭证超时
                onUploadTokenExpired: function (uploadInfo) {
                    // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
                    // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
                    // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
                    let refreshUrl =
                        'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&f=xxx.mp4&VideoId=' +
                        uploadInfo.videoId
                    axios.get(refreshUrl).then(({ data }) => {
                        let uploadAuth = data.UploadAuth
                        uploader.resumeUploadWithAuth(uploadAuth)
                        console.log(
                            'upload expired and resume upload with uploadauth ' +
                                uploadAuth
                        )
                    })
                    self.statusText = '文件超时...'
                },
                // 全部文件上传结束
                onUploadEnd: function (uploadInfo) {
                    console.log('onUploadEnd: uploaded all the files')
                    self.statusText = '文件上传完毕'
                },
            })
            return uploader
        },
    },
}
</script>
<style lang="scss" scoped>
.upload-demo {
    width: 360px;
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    box-sizing: border-box;
    width: 360px;
    height: 180px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    .el-icon-upload {
        font-size: 67px;
        color: #c0c4cc;
        margin: 40px 0 16px;
        line-height: 50px;
    }
    .div__text {
        color: #606266;
        font-size: 14px;
        text-align: center;
        em {
            color: #409eff;
            font-style: normal;
        }
    }
}
</style>
